package com.mew.common.util;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class StringUtils extends org.apache.commons.lang3.StringUtils {

    public final static String basicDataType = "Boolean,Char,Double,Float,Long,Integer,Short,Byte,String";

    private final static String keyForm = "722dd55a8456{}652e9dc72d35b7be{}2f0a16f14ec{}0748b7cff8d0e5e3704ae8";

    //首字母大写
    public static String captureName(String name) {
        name = name.substring(0, 1).toUpperCase() + name.substring(1);
        return  name;
    }

    //aaaBbb  ->  aaa_bbb 大转小
    public static String b2s(String b){
        char[] chars = b.toCharArray();
        HashMap<String,String> map = new HashMap<>();
        for (int i = 0;i<chars.length;i++) {
            char c = chars[i];
            if (c>64&&c<91) {
                map.put(b.substring(i,i+1),new String(new char[]{(char) (c+32)}));
            }
        }

        for (String s : map.keySet()) {

            b = b.replaceAll(s,"_"+map.get(s));
        }

        return b;
    }



    // 加密
    public static String encrypt(String sSrc, String sKey) throws Exception {
        if (sKey == null) {
            System.out.print("Key为空null");
            return null;
        }
        // 判断Key是否为16位
        if (sKey.length() != 16) {
            System.out.print("Key长度不是16位");
            return null;
        }
        byte[] raw = sKey.getBytes("utf-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));

        return new Base64().encodeToString(encrypted);//此处使用BASE64做转码功能，同时能起到2次加密的作用。
    }

    // 解密
    public static String decrypt(String sSrc, String sKey) throws Exception {
        try {
            // 判断Key是否正确
            if (sKey == null) {
                System.out.print("Key为空null");
                return null;
            }
            // 判断Key是否为16位
            if (sKey.length() != 16) {
                System.out.print("Key长度不是16位");
                return null;
            }
            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted1 = new Base64().decode(sSrc);//先用base64解密
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original, "utf-8");
                return originalString;
            } catch (Exception e) {
                System.out.println(e.toString());
                return null;
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }

    //
    public static String toStrByMap(Map<Integer, Long> map, char c, char s){

        StringBuilder builder = new StringBuilder(map.size() * 3);
        map.forEach((k, v) -> {
            builder.append(k).append(c).append(v).append(s);
        });

        builder.deleteCharAt(builder.length()-1);
        return builder.toString();
    }


    // lobbyCode@token@time
    public static boolean checkMewStr(String ciphertext, String key, String lobbyCode, long token, long time){
        try {
            String plaintext = decrypt(ciphertext, key);
            if (StrUtil.isEmpty(plaintext)){return false;}
            String[] str = StrUtil.split(plaintext, "@");
            if (lobbyCode.equals(str[0]) && String.valueOf(token).equals(str[1]) && String.valueOf(time).equals(str[2])){
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("decrypt error", e);
            return false;
        }
    }


    public static String sha256(String text) {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        byte[] bytes = messageDigest.digest(text.getBytes());
        return Hex.encodeHexString(bytes);
    }

    public static boolean isLegal(String data){
        if (StrUtil.isEmpty(data) || data.length() < 6){
            return true;
        }

        String str = sha256(data);
        String s = StrUtil.format(keyForm, data.charAt(2), data.charAt(3), data.charAt(7));
        System.out.println(s);
        return s.equals(str) ? false : true;
    }

    public static void main(String[] args) throws Exception {
        String text = "http://gogo89811898.vcdns.ml:9000/";
        String mew = StringUtils.encrypt(text, "qwertyuiopasdfgh");
        System.out.println(mew);
    }

}
